'use strict';
const jwt = require('jsonwebtoken');
const Controller = require('egg').Controller;
const utils = require('../utils/utils');
class UserController extends Controller {
  async info() {
    const { ctx } = this;

    ctx.body = {
      code: 1,
      data: ctx.userInfo,
    };
  }

  async message_code() {
    const { ctx } = this;
    const createRule = {
      phone: { type: 'string', required: true },
    };
    ctx.validate(createRule, ctx.request.query);
    const { phone } = ctx.request.query;
    ctx.session.code = utils.randomCode(6);
    ctx.body = {
      code: 1,
      message: `验证码已经成功发送到${phone}用户手机，${ctx.session.code}`,
    };

  }

  async login() {
    const { ctx } = this;
    const createRule = {
      phone: { type: 'string', required: true },
      msgCode: { type: 'string', required: true },
    };
    // 校验参数
    ctx.validate(createRule, ctx.request.body);
    const { phone, msgCode } = ctx.request.body;
    if (msgCode === ctx.session.code) {
      const user = await ctx.service.user.find_user(phone);
      if (user) {
        const token = jwt.sign({ ...user }, 'liuyu000');
        ctx.cookies.set('token', token, {
          maxAge: 1000 * 60 * 60 * 24 * 2,
          httpOnly: false,
        });
        ctx.body = {
          code: 1,
          message: '登录成功',
        };
      } else {
        ctx.throw(422, '用户未注册');
      }
    } else {
      ctx.throw(422, '验证码不正确');
    }
  }
}

module.exports = UserController;
